package com.reef.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.reef.dao.StudentRepository;
import com.reef.dto.ReaderDto;
import com.reef.entity.Reader;
import com.reef.service.StudentService;
@Service
public class StudentServiceImpl implements StudentService{
	@Autowired
	private StudentRepository spRepository;
	public List<String> selProfession() {
		return spRepository.selProfession();
	}
	public Page<Reader> findByCondition(ReaderDto sDto, Pageable pageable) {
		// TODO Auto-generated method stub
		Specification<Reader> spec = getSpec(sDto);
		return spRepository.findAll(spec, pageable);
	}
	/**
	 * 单独封装的方法
	 */
	public Specification<Reader> getSpec(final ReaderDto sDto) {
		return new Specification<Reader>() {

			public Predicate toPredicate(Root<Reader> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				//创建SQL表达式
				Predicate p = criteriaBuilder.conjunction();
				//声明表达式的集合
				List<Expression<Boolean>> list = p.getExpressions();
				if (sDto.getR_id()!=0) {
					list.add(criteriaBuilder.equal(root.get("r_id").as(Integer.class),sDto.getR_id() ));
				}
				if (sDto.getName()!=null && sDto.getName()!=" ") {
					list.add(criteriaBuilder.like(root.get("name").as(String.class), "%"+sDto.getName()+"%"));
				}
				if (sDto.getProfession()!=null && sDto.getProfession()!=" ") {
					list.add(criteriaBuilder.like(root.get("profession").as(String.class), "%"+sDto.getProfession()+"%"));
				}
				if (sDto.getStaus()!=0) {
					list.add(criteriaBuilder.equal(root.get("staus").as(Integer.class),sDto.getStaus() ));
				}
				return p;
			}
		};
	}
	public Reader save(Reader reader) {
		// TODO Auto-generated method stub
		return spRepository.save(reader);
	}

	public List<Reader> getAll(String d) {
		// TODO Auto-generated method stub
		return spRepository.findAll();
	}
	public List<Reader> selAll() {
		// TODO Auto-generated method stub
		return spRepository.findAll();
	}
	public Reader insertStu(Reader reader) {
		// TODO Auto-generated method stub
		return spRepository.save(reader);
	}
	public Reader updateStu(Reader reader) {
		// TODO Auto-generated method stub
		return spRepository.save(reader);

	}
	
}
